// 上传图片

import SendUrl from './config.js'
const config = SendUrl.AllUrl

export function UpdataImg(file, callback) {
	var that = this
	var ImgArr = []
	uni.showLoading({
		title: '上传中...',
	})
	for (var i in file) {
		UpImgResolve(file[i], i).then((res) => {
			ImgArr.push(res.img)
			// 当需要上传的文件上传完，返回上传成功的数组
			if (ImgArr.length == file.length) {
				callback(ImgArr)
				uni.hideLoading();
			}
		})
	}
}

export function closeDialog(_this) {
	_this.$bridge.call('closeDialog')
}
export function appFinish(_this) {
	console.log('finish')
	_this.$bridge.call('finish')
}
export function appGoHome(_this) {
	console.log('appGoHome')
	_this.$bridge.call('backHome')
}

export function loginOut(_this) {
	console.log('loginOut')
	_this.$bridge.call('loginOut')
}
export function androidAlbum(_this) {
	console.log('androidAlbum')
	_this.$bridge.call('androidAlbum')
}

export function androidCamera(_this) {
	console.log('androidCamera')
	_this.$bridge.call('androidCamera')
}


export function getOrgId(_this) {
	return new Promise(async function(resolve, reject) {
		const params = {}
		const {
			data
		} = await _this.$request(_this.$Api.orgGet, params, "get")
		if (data.code != 200) return
		resolve(data.data.orgId)
		console.log('getOrgId_____', data)
	})
}
export function isLogin() {
	const userStatus = uni.getStorageSync('userStatus')
	if (!uni.getStorageSync("phone")) {
		uni.showLoading({
			title: '亲！请先登陆...',
		})
		uni.reLaunch({
			url: '/pages/login'
		})
	}
	return
	if (userStatus == 0) {
		uni.showLoading({
			title: '亲！请成为主播可查看...',
		})
		uni.navigateBack()
	}
}
export function UpImgResolve(file, index) {

	return new Promise(function(resolve, reject) {
		uni.uploadFile({
			url: config + "/cos/get-policy-sign",
			filePath: file,
			name: 'file',
			formData: {
				'file': file
			},
			success: function(uploadFileRes) {
				console.log('111', uploadFileRes.data)
				var date = {
					index: index,
					img: uploadFileRes.data
				}
				resolve(date)
			},
			error(res) {
				uni.hideLoading();
			}
		});
	})
}

// 扫码入口
export function scanCode(callback) {
	uni.scanCode({
		success: function(res) {
			callback(res.result)
		}
	});
}
export function getLiveTimeCount(nowTimes, preTimes, callback) {
	console.log('nowTime', nowTimes, 'preTime', nowTimes)
	// if (nowTimes && preTimes) { //如果设置了开始时间
	// 生成当前时间增加的分钟量
	var curTime = new Date();
	var liveCountdown = ''
	let a = nowTimes.replace(/-/g, '/')
	let b = preTimes.replace(/-/g, '/')
	// this.liveCountTimes = setInterval(() => {
	//注：不论安卓还是ios，请将时间如 2020-02-02 20:20:20 转化为 2020/02/02 20:20:20 这种形式后再使用，否则无法转换，如下转换即可↓
	// let transedPreTime=curTime.replace(/-/g,'/') //这里转化时间格式为以/分隔形式
	let nowTime = new Date(a).getTime();
	let preTime = new Date(b).getTime()
	console.log('nowTime', nowTime, 'preTime', preTime)
	// callback(preTime,nowTime)
	let obj = null;
	// if (preTime - nowTime > 0) {
	let time = (preTime - nowTime) / 1000;
	let day = parseInt(time / (60 * 60 * 24));
	let hou = parseInt(time % (60 * 60 * 24) / 3600);
	let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
	let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
	obj = {
		day: day < 10 ? '0' + day : day,
		hou: hou < 10 ? '0' + hou : hou,
		min: min < 10 ? '0' + min : min,
		sec: sec < 10 ? '0' + sec : sec
	};
	liveCountdown = obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'

	callback(liveCountdown)

	// } else {
	// 	// obj = {day:'00',hou:'00',min:'00',sec:'00'};
	// 	// liveCountdown=obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'
	// 	liveCountdown = ""
	// 	callback(2)
	// 	clearInterval(this.liveCountTimes)
	// }
	// }, 1000)

	// } else {
	// 	liveCountdown = ""
	// 	callback(liveCountdown)
	// }
}



export function getWeekStartAndEnd() {
	const oneDayTime = 1000 * 60 * 60 * 24; // 一天里一共的毫秒数
	const today = new Date();
	const todayDay = today.getDay(); // 获取今天是星期几，假设是周3
	const startDate = new Date(
		today.getTime() - oneDayTime * (todayDay - 1)
	);
	const endDate = new Date(today.getTime() + oneDayTime * (7 - todayDay));

	return {
		startDate,
		endDate
	};
}

export function Debounce(_this, callback) {
	if (_this.timeout !== null) clearTimeout(_this.timeout);
	_this.timeout = setTimeout(() => {
		callback(true)
	}, 1000);
}

export function formatDate(date, fmt) {
	var value = date
	var data = new Date(value);
	var month = data.getMonth() + 1;
	var day = data.getDate();
	var year = data.getFullYear();
	var hours = data.getHours();
	var minutes = data.getMinutes();
	var seconds = data.getSeconds();
	// Number(month) < 10 ? '0' + month : month
	// day < 10 ? '0' + day : day
	// hours < 10 ? '0' + hours : hours
	// minutes < 10 ? '0' + minutes : minutes
	// seconds < 10 ? '0' + seconds : seconds
	console.log('dayday', day, hours, minutes, seconds, month)
	const formattedTime =
		`${year}-${month< 10 ? '0' + month : month}-${day< 10 ? '0' + day : day} ${hours< 10 ? '0' + hours : hours}:${minutes< 10 ? '0' + minutes : minutes}:${seconds< 10 ? '0' + seconds : seconds}`;
	console.log("formattedTimeformattedTimeformattedTime", formattedTime)
	return formattedTime;
}

function padLeftZero(str) {
	return ('00' + str).substr(str.length);
}
// date为相加前的时间， days 为 需要相加的天数
export function recentTime(date, days) {
	var date = new Date(date);
	date.setDate(date.getDate() + days);
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var mm = "'" + month + "'";
	var dd = "'" + day + "'";
	if (mm.length == 3) {
		month = "0" + month;
	}
	if (dd.length == 3) {
		day = "0" + day;
	}
	var time = year + "-" + month + "-" + day
	return time;
}




function isObjectEmpty(obj) {

	var status = true
	for (let key in obj) {
		console.log('111', key, obj[key])
		if (obj[key] == '' || obj[key] == undefined || obj[key] == null) {
			return false
		}

	}
	return true;
}
/**
 * 文件大小格式化
 * @param size 文件大小，单位 字节
 */
function formatSize(size) {
	if (!size) return '0.00 KB';

	const kb = size / 1024;
	const mb = kb / 1024;
	const gb = mb / 1024;
	const tb = gb / 1024;

	if (Math.abs(tb) >= 1) {
		return tb.toFixed(2) + ' TB';
	}
	if (Math.abs(gb) >= 1) {
		return gb.toFixed(2) + ' GB';
	}
	if (Math.abs(mb) >= 1) {
		return mb.toFixed(2) + ' MB';
	}
	return kb.toFixed(2) + ' KB';
}

function formatSizeSmall(size) {
	if (!size) return '0.00 KB';

	const kb = size / 1000;
	const mb = kb / 1000;
	const gb = mb / 1000;
	const tb = gb / 1000;

	if (Math.abs(tb) >= 1) {
		return tb.toFixed(2) + ' TB';
	}
	if (Math.abs(gb) >= 1) {
		return gb.toFixed(2) + ' GB';
	}
	if (Math.abs(mb) >= 1) {
		return mb.toFixed(2) + ' MB';
	}
	return kb.toFixed(2) + ' KB';
}

function formatDuration(duration) {
	const days = Math.floor(duration / 60 / 60 / 24)
		.toString()
		.padStart(2, '0');
	const hours = Math.floor((duration / 60 / 60) % 24)
		.toString()
		.padStart(2, '0');
	const minutes = Math.floor((duration / 60) % 60)
		.toString()
		.padStart(2, '0');
	const seconds = Math.floor(duration % 60)
		.toString()
		.padStart(2, '0');

	return {
		days,
		hours,
		minutes,
		seconds
	};
}

let lastCall = 0

/**
 *节流函数
 */
function throttle(fn, delay) {
	const now = new Date().getTime();
	if (now - lastCall < delay) {
		return
	}
	lastCall = now
	fn.apply(this, arguments)

}

export default {
	UpdataImg,
	scanCode,
	getLiveTimeCount,
	getWeekStartAndEnd,
	Debounce,
	formatDate,
	recentTime,
	isObjectEmpty,
	getOrgId,
	isLogin,
	formatSize,
	formatSizeSmall,
	formatDuration,
	throttle,
	closeDialog,
	appFinish,
	appGoHome,
	loginOut,
	androidAlbum,
	androidCamera
}